<template>
  <div class="map-search">
    <div class="search-box">
      <el-input
        v-model="keyword"
        @keyup.enter.native="handleSearch"
        :placeholder="placeholder"
        class="search-input"
      />
      <ul v-if="suggestions.length" class="suggestions-list">
        <li
          v-for="(item, index) in suggestions"
          :key="index" @click="selectSuggestion(item)">
          {{ item.name }} {{ item.address ? `- ${item.address}` : '' }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
declare const AMap: any;

@Component
export default class MapSearch extends Vue {
  @Prop({ required: true }) mapInstance!: any;
  @Prop({ default: '输入地点进行搜索' }) placeholder!: string;
  @Prop({ default: 300 }) debounceTime!: number;
  @Prop({ default: () => ({ city: '内蒙古自治区', type: '' })}) searchOptions!: any;

  private keyword = '';
  private suggestions: any[] = [];
  private autoComplete: any = null;
  private error = false;
  private placeSearch;

  mounted() {
    this.$nextTick(() => {
      if (window.AMap) { // 添加存在性检查
        this.initAutoComplete();
        //this.initSearchService();
      } else {
        console.error('AMap SDK 未加载');
      }
    });
  }

  private initAutoComplete() {
    if (!window.AMap) {
      this.error = true;
      return;
    }

   try {
      this.autoComplete = new AMap.AutoComplete({
        city: this.searchOptions.city,
        type: this.searchOptions.type,
        cityLimit: true,

      });
      this.error = false;
    } catch (e) {
      this.error = true;
      console.error('搜索服务初始化失败:', e);
    }
  }

  private async handleSearch (){
    this.$emit('handle-search', this.keyword);
  }

  async searchMap() {
     if (!this.keyword.trim()) {
      this.suggestions = [];
      return;
    }
    try {
      const result = await this.getSuggestions(this.keyword);
      this.suggestions = result.filter((item: any) => item.location);
      console.log(result)
      this.$message.success('地图搜索完成');
    } catch (error) {
      this.$message.error('地图搜索失败');
    }
}



  /**
   * 获取建议列表
   *
   * @param keyword 关键词
   * @returns 返回建议列表的Promise
   */
  private async getSuggestions(keyword: string): Promise<any[]> {
    // 返回一个Promise对象
    return new Promise((resolve, reject) => {
      // 调用autoComplete的search方法进行搜索
      this.autoComplete.search(keyword, (status: string, result: any) => {
       
        // 如果搜索状态为'complete'，则调用resolve方法，并返回result.tips
        // 如果搜索状态不为'complete'，则调用reject方法，并返回result
        if (status === 'complete') {
        // 过滤无效数据
         // 增强数据过滤
        const validTips = result.tips.filter((tip: any) => 
          tip?.location &&
          typeof tip.name === 'string' &&
          tip.name.trim().length > 0
        );
        resolve(validTips);
        } else {
          reject(result);
        }
      });
    });
  }
  public clearSearch(){
    this.suggestions = [];
  }


  private initSearchService() {
        // 添加容错配置
    this.placeSearch = new AMap.PlaceSearch({
        map: this.mapInstance,
        pageSize: 5,
        extensions: 'all',
        showCover: false,
        city: this.searchOptions.city || '内蒙古自治区',
        lang: 'zh_cn',
        children: 0,
        ...this.searchOptions
    });
    
    // 添加错误监听
    this.placeSearch.on('error', (error: any) => {
        console.error('搜索服务错误:', error);
    });
  }

  private selectSuggestion(item: any) {
    this.$emit('select', item);
    this.suggestions = [];
    this.keyword = item.name;
    
    this.handlePlaceSelect(item);
  }

  @Watch('searchOptions', { deep: true })
  onSearchOptionsChange() {
    
    this.autoComplete.setOptions(this.searchOptions);
  }

   // 添加对地图实例的监听
  @Watch('mapInstance')
  onMapInstanceChange(newMap: any) {
    if (newMap &&  !this.autoComplete) {
      this.initAutoComplete();
    }
  }

  
  private handlePlaceSelect(item: any) {
    this.addMarkers([item])
  }

  private addMarkers(pois: any[]) {
      pois.forEach(poi => {
        const marker = new AMap.Marker({
          position: poi.location,
          title: poi.name,
          map: this.mapInstance  
        });
        marker.on('click', () => this.showInfoWindow(poi));
        this.showInfoWindow(poi);
        this.mapInstance.setCenter(poi.location);
         this.mapInstance.setZoom(15);

      });
  }

  private showInfoWindow(poi: any) {
        const infoWindow = new AMap.InfoWindow({
            content: this.getInfoContent(poi), 
            offset: new AMap.Pixel(0, -30)
        });
        infoWindow.open(this.mapInstance,  poi.location); 
    }

  private getInfoContent(poi: any) {
    console.log(poi);
    return `<div class="custom-info-window">
      <h3>${poi.name}</h3>
      <p>地址：${poi.address || '无'}</p>
      <p>电话：${poi.tel || '无'}</p>
    </div>`;
  }
}
</script>

<style scoped>
.map-search {
  position: relative;
  top: 0px;
  left: 0px;
  z-index: 999;
  width: 200px;
}

.search-box {
  background: white;
  box-shadow: 0 2px 6px rgba(0,0,0,0.3);
  border-radius: 4px;

}


.search-input {
  width: 100%;
  padding: 0px;
  border: none;
  outline: none;
  border-radius: 4px;
}

.suggestions-list {
  list-style: none;
  margin: 0;
  padding: 10px;
  max-height: 200px;
  overflow-y: auto;
  border-top: 1px solid #eee;
}

.suggestions-list li {
  padding: 8px 10px;
  cursor: pointer;
  transition: background 0.2s;
}

.suggestions-list li:hover {
  background: #f5f5f5;
}
</style>